package com.tiku.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tiku.common.ResultJson;
import com.tiku.entity.ChapterInfo;
import com.tiku.entity.ChapterSubInfo;
import com.tiku.entity.UserQuestionLog;
import com.tiku.mapper.ChapterInfoMapper;
import com.tiku.service.ChapterSubInfoService;
import com.tiku.mapper.ChapterSubInfoMapper;
import com.tiku.utils.RedisCache;
import com.tiku.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;

/**
 *
 */
@Service
public class ChapterSubInfoServiceImpl extends ServiceImpl<ChapterSubInfoMapper, ChapterSubInfo>
    implements ChapterSubInfoService{


    @Autowired
    private ChapterSubInfoMapper chapterSubInfoMapper;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ChapterInfoMapper chapterInfoMapper;

    @Override
    public ResultJson getExamChildList(String id,String specification,String menuId) {
        String userId = ThreadLocalUtil.getThreadLocal();
        List<ChapterSubInfo> chapterSubInfos = chapterSubInfoMapper.selectList(new QueryWrapper<ChapterSubInfo>().lambda().eq(ChapterSubInfo::getChapterId, id));
        ChapterSubInfo chapterSubInfo1 = chapterSubInfoMapper.selectById(id);
        ChapterInfo chapterInfo;
        String chapterId=id;
        String standby=id;
       while (chapterSubInfo1 !=null){
           chapterId = chapterSubInfo1.getChapterId();
           standby=chapterId+standby;
           chapterSubInfo1=chapterSubInfoMapper.selectById(chapterId);
       }

/*       //章节id
        chapterInfo = chapterInfoMapper.selectById(chapterId);
        standby=chapterInfo.getId()+standby;*/




        //key : questionLog: + 用户id +类目ID+ 菜单ID+ 章节ID + 子章节ID + 题目ID
        Integer count=0;
        for (ChapterSubInfo chapterSubInfo : chapterSubInfos) {

//            Collection<String> keys = redisCache.keys("questionLog:" + userId +specification+ menuId+ chapterInfo.getId()+chapterSubInfo.getId()+standby+"*");
            Collection<String> keys = redisCache.keys("questionLog:" + userId +specification+ menuId+ standby+chapterSubInfo.getId()+"*");
            chapterSubInfo.setQuestionQuantity(keys.size());
            for (String key : keys) {
                UserQuestionLog userQuestionLog = redisCache.getCacheObject(key);
                if (userQuestionLog.getRightflag()==0) {
                    count++;
                }
            }
            chapterSubInfo.setFailQuantity(count);
        }


        return ResultJson.success(chapterSubInfos);


    }
}




